
Ext.define('Writer.Form', {
    extend: 'Ext.form.Panel',
    alias: 'widget.writerform',

    requires: ['Ext.form.field.Text'],

    initComponent: function(){
        this.addEvents('create');
        Ext.apply(this, {
            activeRecord: null,
            iconCls: 'icon-user',
            frame: true,
            title: 'Modificar Tipo Item',
            defaultType: 'textfield',
            bodyPadding: 5,
            fieldDefaults: {
                anchor: '100%',
                labelAlign: 'right'
            },
            items: [
            {		xtype: 'textfield',			
					name: 'id_tipo_item',
					fieldLabel: 'ID',					
					allowblank: false															
				},
				{
					xtype: 'textfield',
					name: 'nombre',
					fieldLabel: 'Nombre del Tipo Item',					
					allowblank: false
				},{
					xtype: 'textfield',
					name: 'descripcion',
					fieldLabel: 'Descripcion',					
					allowblank: false
				}],
            dockedItems: [{
                xtype: 'toolbar',
                dock: 'bottom',
                ui: 'footer',
                items: ['->', {
                    iconCls: 'icon-save',
                    itemId: 'save',
                    text: 'Save',
                    disabled: true,
                    scope: this,
                    handler: this.onSave
                },{
                    iconCls: 'icon-reset',
                    text: 'Reset',
                    scope: this,
                    handler: this.onReset
                }]
            }]
        });
        this.callParent();
    },

    setActiveRecord: function(record){
        this.activeRecord = record;
        if (record) {
            this.down('#save').enable();
            this.getForm().loadRecord(record);
        } else {
            this.down('#save').disable();
            this.getForm().reset();
        }
    },
    

    onSave: function(){
     			
						this.getForm().submit({
							url: "/modificar_tipo_item",
							params: {
								submit: "submit"
							},
							method: "post",
							waitTitle:'Conectando', 
							waitMsg:'Enviando datos...',
							success: function() {							
								Ext.Msg.alert("Exito", "El tipo item fue modificado con exito");																																																																																									
							},
							failure: function() {
								Ext.Msg.alert("Error", "No se pudo almacenar el tipo item");
							}	
						})
				
        
        
        
        
    },

    onReset: function(){
        this.setActiveRecord(null);
        this.getForm().reset();
    }
});

Ext.define('Writer.Grid', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.writergrid',

    requires: [
        'Ext.grid.plugin.CellEditing',
        'Ext.form.field.Text',
        'Ext.toolbar.TextItem'
    ],

    initComponent: function(){

        this.editing = Ext.create('Ext.grid.plugin.CellEditing');

        Ext.apply(this, {
            iconCls: 'icon-grid',
            frame: true,
            plugins: [this.editing],
            dockedItems: [{
                xtype: 'toolbar',
                items: [{
                    iconCls: 'icon-add',
                    text: 'Add',
                    scope: this,
                    handler: function onItemClick(){
						window.open('registrar_tipo_item')
						}
                }, {
                    iconCls: 'icon-delete',
                    text: 'Delete',
                    disabled: true,
                    itemId: 'delete',
                    scope: this,
                    handler: this.onDeleteClick
                }]
            }],
            columns: [{
                text: 'ID',
                width: 40,
                sortable: true,
                dataIndex: 'id__tipo_item'
            },{
                header: 'Nombre _tipo_item',
                flex: 1,
                sortable: true,
                dataIndex: 'nombre',
                field: {
                    type: 'textfield'
                }
            },{
                header: 'Descripcion',
                flex: 1,
                sortable: true,
                dataIndex: 'descripcion',
                field: {
                    type: 'textfield'
                }
            }]
        });
        this.callParent();
        this.getSelectionModel().on('selectionchange', this.onSelectChange, this);
    },
    
    onSelectChange: function(selModel, selections){
        this.down('#delete').setDisabled(selections.length === 0);
    },

    onSync: function(){
        this.store.sync();
    },

    onDeleteClick: function(){
        var selection = this.getView().getSelectionModel().getSelection()[0];
        if (selection) {
		var id_tipo_item = this.getView().getSelectionModel().getSelection()[0].data['id_tipo_item'];	
            
											Ext.Msg.confirm('Eliminar', 'Desea eliminar el tipo item?', function(btn){
												
												if(btn == 'yes') {
													
													Ext.Ajax.request({
														url: '/delete_tipo_item',
														params: {
															id_tipo_item: id_tipo_item
														},
														success: function() {
															Ext.Msg.alert('Felicidades', 'Ha eliminado el tipo item', function(btn){																
																grid.store.load();
																
															})
														},
														failure: function() {
															Ext.Msg.alert('Error', 'No se pudo eliminar el tipo item')
														}
													})
												}											
											})                      
            	
            this.store.remove(selection);
        }
    },

    onAddClick: function(){
        var rec = new Writer.Person({
            nombre: '',
            descripcion: ''            
                        
        }), edit = this.editing;

        edit.cancelEdit();
        this.store.insert(0, rec);
        edit.startEditByPosition({
            row: 0,
            column: 1
        });
    }
});

Ext.define('TipoItem', {
    extend: 'Ext.data.Model',
    fields: [
			{name: 'id_tipo_item',  type: 'int'},
			{name: 'nombre',   type: 'string'},
			{name: 'descripcion',   type: 'string'},					
        ]
});

Ext.require([
    'Ext.data.*',
    'Ext.tip.QuickTipManager',
    'Ext.window.MessageBox'
]);

Ext.onReady(function(){
    Ext.tip.QuickTipManager.init();
    var store = Ext.create('Ext.data.Store', {
        model: 'TipoItem',
        autoLoad: true,
        autoSync: true,
        proxy: {
            type: 'ajax',
            api: {
                read: '/consulta_tipo_item',
                create: '/modificar_tipo_items',
                update: '/modificar_tipo_items',
                destroy: '/delete_tipo_items'
            },
            reader: {
                type: 'json',
                successProperty: 'success',
                root: 'tipo_items',
                messageProperty: 'message'
            },
            writer: {
                type: 'json',
                writeAllFields: false,
                root: 'tipo_items'
            },
            listeners: {
                exception: function(proxy, response, operation){
                    Ext.MessageBox.show({
                        title: 'REMOTE EXCEPTION',
                        msg: operation.getError(),
                        icon: Ext.MessageBox.ERROR,
                        buttons: Ext.Msg.OK
                    });
                }
            }
        },
        listeners: {
            write: function(proxy, operation){
                if (operation.action == 'destroy') {
                    main.child('#form').setActiveRecord(null);
                }
                Ext.example.msg(operation.action, operation.resultSet.message);
            }
        }
    });

    var main = Ext.create('Ext.container.Container', {
        padding: '0 0 0 20',
        width: 500,
        height: 450,
        renderTo: document.body,
        layout: {
            type: 'vbox',
            align: 'stretch'
        },
        items: [{
            itemId: 'form',
            xtype: 'writerform',
            height: 200,
            margins: '0 0 10 0',
            listeners: {
                create: function(form, data){
                    store.insert(0, data);
                }
            }
        }, {
            itemId: 'grid',
            xtype: 'writergrid',
            title: 'TipoItem List',
            flex: 1,
            store: store,
            listeners: {
                selectionchange: function(selModel, selected) {
                    main.child('#form').setActiveRecord(selected[0] || null);
                }
            }
        }]
    });
});
